package com.crp.unitalinforbaseplat.app.sys.security

import com.crp.unitalinforbaseplat.app.sys.service.UserService
import com.crp.unitalinforbaseplat.app.unitalinforbaseplat.entity.Principal
import org.apache.shiro.authc.AuthenticationInfo
import org.apache.shiro.authc.AuthenticationToken
import org.apache.shiro.authc.SimpleAuthenticationInfo
import org.apache.shiro.authc.UsernamePasswordToken
import org.apache.shiro.authz.AuthorizationInfo
import org.apache.shiro.authz.SimpleAuthorizationInfo
import org.apache.shiro.realm.AuthorizingRealm
import org.apache.shiro.subject.PrincipalCollection
import org.springframework.beans.factory.annotation.Autowired

/**
 * @program: squarenavigationsys
 * @description:MyRealm
 * @author:  chenzhicai
 * @create: 2018-11-03-20-21
 **/
class MyRealm : AuthorizingRealm() {

    @Autowired
    private val userService: UserService? = null


    override fun doGetAuthenticationInfo(authtoken: AuthenticationToken?): AuthenticationInfo? {

        val token = authtoken as UsernamePasswordToken
        // 校验用户名密码
        try {
            val user = userService!!.verify(token.username)
            if (user != null) {
                val principal = Principal()
                principal.setId(user.id.toLong())
                principal.userName = user.username
                principal.userId = user.userId
                principal.email = user.email
                principal.age = user.age
                principal.roleName = user.roleName
                val authenticationInfo = SimpleAuthenticationInfo(
                        principal, //用户名
                        user.password, //密码
                        name  //realm name
                )
                return authenticationInfo
            } else {
                return null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return null
    }

    override fun doGetAuthorizationInfo(principals: PrincipalCollection?): AuthorizationInfo {
        println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        val info = SimpleAuthorizationInfo()
        val userinfo = principals!!.getPrimaryPrincipal() as Principal
        val user = userService!!.verify(userinfo.userId)
        val permission = userService.getUserPermission(user.id.toString())
        for(item in permission){
            info.addStringPermission(item.perms)
        }
        println("permission is${info.stringPermissions}")
        return info
    }


}